#include "ServerUI.h"
#include <QMessageBox>

ServerUI::ServerUI(QWidget *parent)
    : QWidget(parent){
    setWindowTitle(tr("TCP Server"));

    infoListWidget = new QListWidget;
    LabelPort = new QLabel(tr("port :"));
    LineEditPort = new QLineEdit;
    BtnServerSwitch = new QPushButton(tr("create"));

    mainLayout = new QGridLayout(this);
    mainLayout->addWidget(infoListWidget,0,0,4,2);
    mainLayout->addWidget(LabelPort,5,0);
    mainLayout->addWidget(LineEditPort,5,1);
    mainLayout->addWidget(BtnServerSwitch,6,0,1,2);

    isCreated = false;
    port = 8888;
    LineEditPort->setText(QString::number(port));

    connect(this,SIGNAL(createServer()),this,SLOT(slotCreateServer()));
    connect(BtnServerSwitch,SIGNAL(clicked(bool)),this,SLOT(slotServerSwitch()));
}

ServerUI::~ServerUI(){
}

void ServerUI::slotServerSwitch(){
    if(!isCreated){
        emit createServer();
    }
    else{
        emit closeServer();
        BtnServerSwitch->setText(tr("create"));
        isCreated = false;
    }
}

void ServerUI::slotupdateServerUI(QString str){
     infoListWidget->addItem(str);
}

void ServerUI::slotCreateServer(){
    int temp = LineEditPort->text().toInt();
    if(LineEditPort->text().isEmpty() || temp < 1024){
        QMessageBox::information(this,tr("Error"),tr("please input a valid port!"));
    }
    else{
        port = temp;
        server = new Server(this,port);
        connect(server,SIGNAL(updateServerUI(QString)),this,SLOT(slotupdateServerUI(QString)));
        connect(this,SIGNAL(closeServer()),server,SLOT(slotClose()));
        BtnServerSwitch->setText(tr("close"));    //if succeed. I'll fix it later;
        isCreated = true;
    }
}
